package net.j4love.netty.inaction.c5;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import org.junit.Test;

/**
 * @author he peng
 * @create 2018/6/12 16:46
 * @see
 */
public class ByteBufTest {

    @Test
    public void byteBufTest0() throws Exception {
        ByteBuf buf = Unpooled.buffer();
        System.out.println("init bytebuf -> " + buf);

        buf.writeCharSequence("abc" , CharsetUtil.UTF_8);
        System.out.println("write after bytebuf -> " + buf);

        CharSequence cs = buf.getCharSequence(0, 1, CharsetUtil.UTF_8);
        System.out.println("get CharSequence -> " + cs);
        System.out.println("get CharSequence after bytebuf -> " + buf);

        cs = buf.readCharSequence(3, CharsetUtil.UTF_8);
        System.out.println("read CharSequence -> " + cs);
        System.out.println("read CharSequence after bytebuf -> " + buf);

        buf.discardReadBytes();
        System.out.println("discardReadBytes after bytebuf -> " + buf);

        // discardReadBytes 不会真正丢弃数据 , 只是改变索引的值
        System.out.println("discardReadBytes after get -> " + buf.getCharSequence(0, 3, CharsetUtil.UTF_8));
    }

    @Test
    public void compositeByteBufTest0() throws Exception {
        CompositeByteBuf buf = Unpooled.compositeBuffer();
        buf.addComponents(Unpooled.copiedBuffer("月光白得很" , CharsetUtil.UTF_8) ,
                Unpooled.copiedBuffer("南方像莎士比亚一样", CharsetUtil.UTF_8));
        for (ByteBuf byteBuf : buf) {
            System.out.println(byteBuf.toString(CharsetUtil.UTF_8));
        }

        System.out.println("==============================================================");
        buf.removeComponent(0);

        for (ByteBuf byteBuf : buf) {
            System.out.println(byteBuf.toString(CharsetUtil.UTF_8));
        }
    }
}
